package com.ch.doudemo.activity;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.ch.doudemo.R;
import com.ch.doudemo.base.BaseRecAdapter;
import com.ch.doudemo.base.BaseRecViewHolder;
import com.ch.doudemo.base.MyApp;
import com.ch.doudemo.bean.CommonReqBean;
import com.ch.doudemo.bean.CommonResBean;
import com.ch.doudemo.bean.MessageBean;
import com.ch.doudemo.bean.UrlBean;
import com.ch.doudemo.bean.VideoListReqBean;
import com.ch.doudemo.bean.VideoListResBean;
import com.ch.doudemo.util.HttpClientUtil;
import com.ch.doudemo.util.MyConstant;
import com.ch.doudemo.util.MyStringCallback;
import com.ch.doudemo.widget.MyVideoPlayer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 视频列表
 */
public class ListActivity extends AppCompatActivity {

    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.videoListSRL)
    SwipeRefreshLayout videoListSRL;
    private List<VideoListResBean.Responsebody> urlList;
    private ListVideoAdapter videoAdapter;
    private int firstVisibleItem;
    private int lastVisibleItem;
    private MyApp myApp;
    private int curPage = 1;
    private TextView curGoodTV; //标记点击的布局

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        init();
        requestVideoList(0);
    }

    private void init() {
        myApp = (MyApp) getApplication();
        urlList = new ArrayList<>();
//        urlList.add("http://82.156.54.193:8888/upload/Rec%200001.mp4");
        videoAdapter = new ListVideoAdapter(urlList);
        rvList.setLayoutManager(new LinearLayoutManager(ListActivity.this));
        rvList.setAdapter(videoAdapter);
        videoListSRL.setRefreshing(true);
        videoListSRL.setColorSchemeResources(R.color.bar_grey);
        videoListSRL.setOnRefreshListener(new MyRefreshLinstener());
//        addListener();
        rvList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //判断状态
                switch (newState) {
                    // 当不滚动时
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:// 是当屏幕停止滚动时
                        // 判断滚动到顶部
                        if (!rvList.canScrollVertically(-1)) {
                            videoListSRL.setEnabled(true);
                        } else {
                            videoListSRL.setEnabled(false);
                        }

                        if (!rvList.canScrollVertically(1)) { // 到达底部
                            requestVideoList(curPage);
                        }
                        break;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    /**
     * 下拉刷新
     */
    class MyRefreshLinstener implements SwipeRefreshLayout.OnRefreshListener {

        @Override
        public void onRefresh() {
            requestVideoList(0);
        }
    }

    private void requestVideoList(int pPage) {
        VideoListReqBean videoListReqBean = new VideoListReqBean();
        videoListReqBean.setPageNo(pPage + 1 + "");
        String jsonStr = JSON.toJSONString(videoListReqBean);
        HttpClientUtil.postReq(UrlBean.ReqVideoList, myApp.getToken(), jsonStr, this, new MyStringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != videoListSRL) {
                    videoListSRL.setRefreshing(false);
                }
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e("bugggggggggggggg", "requestVideoList = " + response);
                VideoListResBean videoListResBean = JSON.parseObject(response, VideoListResBean.class);
                if ("0".equals(videoListResBean.getErrcode())) {
                    if (0 == pPage) {
                        curPage = 1;
                        videoAdapter.setNewData(videoListResBean.getData());
                        videoAdapter.notifyDataSetChanged();
                    } else {
                        if (null != videoListResBean.getData() && 0 != videoListResBean.getData().size()) {
                            videoAdapter.getData().addAll(videoListResBean.getData());
                            videoAdapter.notifyDataSetChanged();
                            curPage++;
                        }
                    }
                }
                if (null != videoListSRL) {
                    videoListSRL.setRefreshing(false);
                }

            }
        });


    }


    private void addListener() {

        rvList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                firstVisibleItem = layoutManager.findFirstVisibleItemPosition();
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();

            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE://停止滚动
                        /**在这里执行，视频的自动播放与停止*/
                        autoPlayVideo(recyclerView);
                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING://拖动
                        autoPlayVideo(recyclerView);
                        break;
                    case RecyclerView.SCROLL_STATE_SETTLING://惯性滑动
                        MyVideoPlayer.releaseAllVideos();
                        break;
                }

            }
        });
    }

    /**
     * 自动播放
     */
    private void autoPlayVideo(RecyclerView recyclerView) {

        if (firstVisibleItem == 0 && lastVisibleItem == 0 && recyclerView.getChildAt(0) != null) {

            MyVideoPlayer videoView = null;
            if (recyclerView != null && recyclerView.getChildAt(0) != null) {
                videoView = recyclerView.getChildAt(0).findViewById(R.id.mp_video);
            }
            if (videoView != null) {
                if (videoView.state == MyVideoPlayer.STATE_NORMAL || videoView.state == MyVideoPlayer.STATE_PAUSE) {
                    videoView.startVideo();
                }
            }
        }

        for (int i = 0; i <= lastVisibleItem; i++) {
            if (recyclerView == null || recyclerView.getChildAt(i) == null) {
                return;
            }


            MyVideoPlayer
                    videoView = recyclerView.getChildAt(i).findViewById(R.id.mpListVideo);
            if (videoView != null) {

                Rect rect = new Rect();
                //获取视图本身的可见坐标，把值传入到rect对象中
                videoView.getLocalVisibleRect(rect);
                //获取视频的高度
                int videoHeight = videoView.getHeight();

                if (rect.top <= 100 && rect.bottom >= videoHeight) {
                    if (videoView.state == MyVideoPlayer.STATE_NORMAL || videoView.state == MyVideoPlayer.STATE_PAUSE) {
                        videoView.startVideo();
                    }
                    return;
                }

                MyVideoPlayer.releaseAllVideos();
            } else {
                MyVideoPlayer.releaseAllVideos();
            }

        }

    }


    @Override
    public void onPause() {
        super.onPause();
        MyVideoPlayer.releaseAllVideos();
    }


    class ListVideoAdapter extends BaseRecAdapter<VideoListResBean.Responsebody, VideoViewHolder> {


        public ListVideoAdapter(List<VideoListResBean.Responsebody> list) {
            super(list);
        }

        @Override
        public void onHolder(VideoViewHolder holder, VideoListResBean.Responsebody bean, int position) {
            holder.mpListVideo.setUp(bean.getV_url(), bean.getUser_name() + bean.getCreate_date(), MyVideoPlayer.STATE_NORMAL);
//            if (position == 0) {
//                holder.mp_video.startVideo();
//            }
            Glide.with(context).load(bean.getV_url()).into(holder.mpListVideo.thumbImageView);
            holder.tvListTitle.setText(bean.getUser_name() + bean.getCreate_date());
            holder.plBT.setText("评论" + bean.getComment_num());
            if (bean.isGood()) {
                holder.dzBT.setText("♥已赞" + bean.getGood_num());
            } else {
                holder.dzBT.setText("♡点赞" + bean.getGood_num());
            }

            holder.plBT.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    curGoodTV = holder.dzBT;
                    Intent intent = new Intent(ListActivity.this, SingleVideoActivity.class);
                    intent.putExtra(MyConstant.Str1, bean);
                    intent.putExtra(MyConstant.Str2, bean.getComment_num());
                    intent.putExtra(MyConstant.Str3, holder.dzBT.getText());
                    intent.putExtra(MyConstant.Str4, holder.tvListTitle.getText().toString());
                    startActivityForResult(intent,0);
                }
            });

            holder.dzBT.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    requestGood(bean.getId(), holder.dzBT);
                }
            });
        }


        @Override
        public VideoViewHolder onCreateHolder() {
            return new VideoViewHolder(getViewByRes(R.layout.item_video));
        }

    }


    private void requestGood(String pVideoID, TextView pView) {
        String reqUrl;
        //此处简单一写 只为了获取点赞数量显示  这么写肯定不好~ 根据具体需求处理
        int curGoodNum = Integer.parseInt(pView.getText().toString().replace("♡点赞", "").replace("♥已赞", ""));
        if (pView.getText().toString().contains("♥")) {
            reqUrl = UrlBean.ReqCancelGood;
        } else {
            reqUrl = UrlBean.ReqAddGood;
        }
        CommonReqBean commonReqBean = new CommonReqBean();
        commonReqBean.setV_id(pVideoID);
        String jsonStr = JSON.toJSONString(commonReqBean);
        HttpClientUtil.postReq(reqUrl, myApp.getToken(), jsonStr, this, new MyStringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                Log.e("buggggggggggg", "response = " + response);
                CommonResBean commonResBean = JSON.parseObject(response, CommonResBean.class);
                if ("0".equals(commonResBean.getErrcode())) {
                    if (pView.getText().toString().contains("♥")) {
                        pView.setText("♡点赞" + (curGoodNum - 1) + "");
                    } else {
                        pView.setText("♥已赞" + (curGoodNum + 1) + "");
                    }

                }

            }
        });

    }

    public class VideoViewHolder extends BaseRecViewHolder {
        public View rootView;
        public MyVideoPlayer mpListVideo;
        public TextView tvListTitle;
        public TextView plBT;
        public TextView dzBT;

        public VideoViewHolder(View rootView) {
            super(rootView);
            this.rootView = rootView;
            this.mpListVideo = rootView.findViewById(R.id.mpListVideo);
            this.tvListTitle = rootView.findViewById(R.id.tvListTitle);
            this.plBT = rootView.findViewById(R.id.plBT);
            this.dzBT = rootView.findViewById(R.id.dzBT);
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(0 == requestCode){

        }
    }

    @Subscribe
    public void onEvent(MessageBean event) {
        if (MyConstant.Msg1.equals(event.getKey())) {
            curGoodTV.setText(event.getValues());
        }
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
